import axios from 'axios'
import qs from 'qs'

let _instance
const _p = function (obj, key, val) {
  if (val) {
    obj[key] = val
  }
}
const _createAxiosInstance = function ({
  method = 'post',
  data = {},
  params = {},
  isUrlParams = true,
  withCredentials = false,
  timeout = 300000,
  responseType = 'json',
  headers = {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json;charset=utf-8'
  }
} = {}) {
  let options = {}
  _p(options, 'method', method)
  if (method === 'post' || method === 'put' || method === 'patch') {
    options.data = data
  } else if (method === 'get' || method === 'delete') {
    if (isUrlParams) {
      options.params = params
    } else {
      options.data = params
    }
  }
  options.data = data
  options.params = params
  _p(options, 'withCredentials', withCredentials)
  _p(options, 'timeout', timeout)
  _p(options, 'responseType', responseType)
  _p(options, 'headers', headers)
  _instance = axios.create(options)
  _instance.interceptors.request.use(config => {
    if (config.method === 'post' || config.method === 'put' || config.method === 'patch') {
      let isFormData = config.data.isFormData
      delete config.data.isFormData
      if (isFormData) {
        config.data = qs.stringify(config.data)
      } else {
        config.data = JSON.stringify(config.data)
      }
    }
    return config
  }, error => {
    return Promise.reject(error)
  })
  _instance.interceptors.response.use(response => {
    if (!response.data || response.data.length === 0) {
      console.log('后台传来的data为空或者为undefined')
    }
    return response
  }, error => {
    return Promise.reject(error)
  })
}
_createAxiosInstance()
/**
 * 拦截请求
 */
axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})
/**
 * 拦截响应
 */
axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})
/**
 * 封装ajax交易
 * @param url 请求地址
 * @param method 请求方法
 * @param params 请求参数
 * @param showLoading 是否显示 loading  true：显示 false：不显示
 * @param needHandlerErr 是否公共拦截报错 true 公共拦截 false 自行定义报错
 * @param isFormData 是否是form key-value 传参的方式 默认上传字符串
 * @param options 请求的头的其它配置 eg：headers: {'Content-Type': 'application/json;charset=utf-8'}
 * @returns {Promise<any>}
 */
const ajax = function (url, {
  method = 'post',
  params = {},
  showLoading = true,
  needHandlerErr = true,
  isFormData = false,
  isUrlParams = true,
  headerOpts = {}
} = {}) {
  let options = {
    url,
    method,
    ...headerOpts
  }
  if (method === 'post' || method === 'put' || method === 'patch') {
    options.data = params
    options.data.isFormData = isFormData
  } else if (method === 'get' || method === 'delete') {
    if (isUrlParams) {
      options.params = params
    } else {
      options.data = params
    }
  }
  let _this = this
  return new Promise((resolve, reject) => {
    showLoading && _this.uiLoading()
    _instance.request(options).then(res => {
      let { data } = res
      if (!(data.status === '000000')) {
        if (needHandlerErr) {
          showLoading && _this.uiHideLoading()
          if (data.msg) {
            _this.uiDialog(data.msg, {
              title: '错误提示'
            })
          } else {
            _this.uiDialog(`未解析到服务器端错误,错误码：【${data.status}】`, {
              title: '错误提示'
            })
          }
          return reject(data)
        }
        reject(data)
      } else {
        showLoading && _this.uiHideLoading()
        resolve(data)
      }
    }).catch(err => {
      // 细化错误消息
      if (err && err.response) {
        showLoading && _this.uiHideLoading()
        const errMsg = err.message
        if (errMsg.includes('Network Error')) {
          _this.uiDialog('网络异常，请稍后尝试', {
            title: '错误提示'
          })
        } else if (errMsg.includes('timeout')) {
          _this.uiDialog('请求超时，请稍后尝试', {
            title: '错误提示'
          })
        } else {
          let errmsg
          switch (err.response.status) {
            case 400:
              errmsg = '请求错误'
              break
            case 401:
              errmsg = '未授权，请登录'
              break
            case 403:
              errmsg = '拒绝访问'
              break
            case 404:
              let errTransCode = err.response.config.url.slice(err.response.config.url.lastIndexOf('/') + 1)
              errmsg = `404 找不到请求的资源: ${errTransCode}`
              break
            case 408:
              errmsg = '请求超时'
              break
            case 500:
              errmsg = `500 服务器内部错误 [${errMsg}]`
              break
            case 501:
              errmsg = '服务未实现'
              break
            case 502:
              errmsg = '网关错误'
              break
            case 503:
              errmsg = '服务不可用'
              break
            case 504:
              errmsg = '网关超时'
              break
            case 505:
              errmsg = 'HTTP版本不受支持'
              break
            case 530:
              errmsg = '登录超时，请重新登录'
              break
            default:
              errmsg = `请求出错 [${errMsg}]`
              break
          }
          if (err.response.status === 530) {
            _this.uiConfirm(errmsg, {
              title: '错误提示',
              confirmCallback: () => {
                // _this.psPageNext('/')
                window.location.href = '/'
              }
            })
          } else {
            _this.uiDialog(errmsg, {
              title: '错误提示'
            })
          }
        }
      }
    }).finally(
      // 关闭loading 加载遮罩
      // _this.uiHideLoading()
    )
  })
}
export default {
  ajax
}
